package cn.weekimwee.firstlineofcodeforkotlin.unit10.download

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.view.View
import cn.weekimwee.firstlineofcodeforkotlin.BaseActivity
import cn.weekimwee.firstlineofcodeforkotlin.R
import kotlinx.android.synthetic.main.activity_download.*

class DownloadActivity : BaseActivity() {

    private var downloadBinder :DownloadService.DownloadBinder?=null

    private val connection = object :ServiceConnection{
        override fun onServiceDisconnected(name: ComponentName?) {

        }

        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            downloadBinder = service as DownloadService.DownloadBinder?
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_download)
        start_download.setOnClickListener { it.onClick() }
        pause_download.setOnClickListener { it.onClick() }
        cancel_download.setOnClickListener { it.onClick() }
        val intent = Intent(this,DownloadService::class.java)
        startService(intent)
        bindService(intent,connection, Context.BIND_AUTO_CREATE)
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(connection)
    }

    private fun View.onClick() {
        when (this.id) {
            R.id.start_download -> {
                val url = "https://raw.githubusercontent.com/guolindev/eclipse/master/eclipse-inst-win64.exe"
                downloadBinder?.startDownload(url)
            }
            R.id.pause_download -> {
                downloadBinder?.pauseDownload()
            }
            R.id.cancel_download -> {
                downloadBinder?.cancelDownload()
            }
        }
    }
}
